﻿using System;
using System.Collections.Generic;
#if DEBUG
using System.Diagnostics;
#endif // #if DEBUG
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using FRL.DebtChased.Extensions;
using FRL.DebtChased.Repository;
using FRL.DebtChased.Repository.ViewModels;
using FRL.DebtChased.Website;

namespace WebApplication.Finance.Controls
{

	/// <summary>
	/// Declaration of ClientAlertsCtrl class
	/// </summary>
	public partial class ClientAlertsCtrl : System.Web.UI.UserControl
	{

		/////////////////////////////////////////////////////////////
		// Constants

		private const string ContextModeltag = "ContextModel";
		private const string ClientIdTag = "ClientRecordId";

		/////////////////////////////////////////////////////////////
		// Attributes

		private ClientAlertsModel m_contextModel;
		public ClientAlertsModel ContextModel
		{
			get
			{
				if (m_contextModel == null)
					m_contextModel = ViewState[ContextModeltag] as ClientAlertsModel;
				return m_contextModel;
			}
			private set
			{
				ViewState[ContextModeltag] = value;
			}
		}

		private bool m_bRebindTargetUsers = false;

		/////////////////////////////////////////////////////////////
		// Event handlers

		protected override void OnPreRender(EventArgs e)
		{

			// Call base-class function
			base.OnPreRender(e);

			// Bind the grid to the data
			gridAlerts.DataSource = ContextModel.Elements;
			gridAlerts.DataBind();

			// Bind the send time
			cboSendTimeMinutes.SelectedValue = ContextModel.SendTimeMinutes.ToString();

			// If rebinding...
			if (m_bRebindTargetUsers)
				_bindNewAlertTargetUser();

			// Show/hide controls
			pnlAddAlert.Visible = (cboNewTarget.Items.Count > 0);

		}

		protected void Page_Load(object sender, EventArgs e)
		{

			// If this is a postback...
			if (this.IsPostBack)
			{

				// Get the model
				ClientAlertsModel model = ContextModel;
#if DEBUG
				Debug.Assert(model != null);
#endif // #if DEBUG

				// Update model from grid	
#if DEBUG			
				Debug.Assert(gridAlerts.Rows.Count == model.Elements.Count);
#endif // #if DEBUG
				for (int iRowIndex = 0; iRowIndex < gridAlerts.Rows.Count; iRowIndex++)
				{

					// Get the id and controls
					int id = int.Parse(gridAlerts.DataKeys[iRowIndex].Value.ToString());
					CheckBox chkFilterAll = gridAlerts.Rows[iRowIndex].FindControl("chkFilterAll") as CheckBox;

					// Update model from grid controls
					ClientAlertsModel.Element el = model.FindByClientAlertId(id);
					if(el!=null)
					{
						el.FilterAll = chkFilterAll.Checked;
					}
#if DEBUG
					else
						Debug.Assert(false);
#endif // #if DEBUG

				}

				// Update the send time
				model.SendTimeMinutes = int.Parse(cboSendTimeMinutes.SelectedValue);

			}
			else
			{
#if DEBUG
				Debug.Assert(ContextModel == null);
#endif // #if DEBUG

				// Rebind on pre-render
				m_bRebindTargetUsers = true;

				// Declare an entities object
				using (DebtChasedEntities ent = new DebtChasedEntities())
				{

					// Load the workflow list model
					ContextModel = new ClientAlertsModel(ent);

				}

				// Load the send time
				Dictionary<int, string> mapHours = ExtensionsForWebsites.LoadTimeMinutes();
				cboSendTimeMinutes.BindToDictionary(mapHours);

				// Set the grid border
				gridAlerts.RowStyle.BorderColor = MyApplication.BindMyApplication().SecondaryWebColor;

			}

		}

		protected void gridAlerts_RowDataBound(object sender, GridViewRowEventArgs e)
		{

			// If this is a data-row...
			if (e.Row.RowType == DataControlRowType.DataRow)
			{

				// Get the model element
				ClientAlertsModel.Element el = e.Row.DataItem as ClientAlertsModel.Element;

				// Set filter-all checkbox
				CheckBox chkFilterAll = e.Row.FindControl("chkFilterAll") as CheckBox;
				chkFilterAll.Checked = (el.FilterAll);

			}

		}

		protected void gridAlerts_RowCommand(object sender, GridViewCommandEventArgs e)
		{

			// Check the grid view object
			GridView gridAlerts = sender as GridView;

			// Get row index
			int iRow = int.Parse(e.CommandArgument.ToString());

			// Convert argument to id
			int iClientAlertId = int.Parse(gridAlerts.DataKeys[iRow].Value.ToString());

			// Compare commands
			if (e.CommandName == "DeleteAlert")
			{

				// Get the model
				ClientAlertsModel model = ContextModel;
#if DEBUG
				Debug.Assert(model != null);
#endif // #if DEBUG

				// Delete from the model
				ClientAlertsModel.Element el = model.FindByClientAlertId(iClientAlertId);
				if (el != null)
				{

					// Remove, rebind and reload user control
					model.Elements.Remove(el);

					// Bind the new target combo
					m_bRebindTargetUsers = true;

				}
#if DEBUG
				else
					Debug.Assert(false);
#endif // #if DEBUG

			}

		}

		protected void butAdd_Click(object sender, EventArgs e)
		{

			// Get the model
			ClientAlertsModel model = ContextModel;
#if DEBUG
			Debug.Assert(model != null);
#endif // #if DEBUG

			// Get the new user
			int iUserId = int.Parse(cboNewTarget.SelectedValue.ToString());

			// Get the next new alert id
			int iNewAlertId = model.GetNextNewId();

			// Get the filter-all
			bool bFilterAll = chkNewFilterAll.Checked;

			// Create a new model element
			ClientAlertsModel.Element el = new ClientAlertsModel.Element(iNewAlertId);
			el.UserId = iUserId;
			el.UserAsText = cboNewTarget.SelectedItem.ToString();
			el.FilterAll = bFilterAll;
			el.ClientAlertId = iNewAlertId;
			model.Elements.Add(el);

			// Bind the new target combo
			m_bRebindTargetUsers = true;

		}

		/////////////////////////////////////////////////////////////
		// Operations

		private void _bindNewAlertTargetUser()
		{

			// Declare an entities object
			using(DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Load the user map
				Dictionary<int, string> userMap = User.GetDictionary(ent, Definitions.AnyFinUserRole, false);

				// Get the model
				ClientAlertsModel model = ContextModel;
#if DEBUG
				Debug.Assert(model != null);
#endif // #if DEBUG

				// Remove users already in the model
				foreach (ClientAlertsModel.Element el in model.Elements)
					userMap.Remove(el.UserId);

				// Load the dropdown
				cboNewTarget.BindToDictionary(userMap);
				if(cboNewTarget.Items.Count > 0)
					cboNewTarget.SelectedIndex = 0;

			}

		}

	}

}